package com.abe.libcore.view.recyclerview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.RecyclerView;

public class RecyclerViewTool {
    public static RecyclerView.ItemDecoration color(Context context, int color) {
        return normal(context, new ColorDrawable(color));
    }

    public static RecyclerView.ItemDecoration colorRes(Context context, int colorRes) {
        return normal(context, new ColorDrawable(context.getResources().getColor(colorRes)));
    }

    public static RecyclerView.ItemDecoration normal(Context context, int drawableRes) {
        return normal(context, context.getResources().getDrawable(drawableRes));
    }

    public static RecyclerView.ItemDecoration normal(Context context, Drawable drawable) {
        //添加自定义分割线
        DividerItemDecoration divider = new DividerItemDecoration(context, DividerItemDecoration.VERTICAL);
        divider.setDrawable(new BitmapDrawable(context.getResources(),drawableReset(drawable)));
        return divider;
    }

    /**
     * 处理无宽高资源
     *
     * @param drawable drawable
     */
    private static Bitmap drawableReset(Drawable drawable) {
        //取drawable的宽高(如果存在宽高问题)
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        if (width <= 0) {
            width = 1;
        }
        if (height <= 0) {
            height = 1;
        }
        //取drawable的颜色格式
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE
                ? Bitmap.Config.ARGB_8888
                : Bitmap.Config.RGB_565;
        //创建对应的bitmap
        Bitmap bitmap = Bitmap.createBitmap(width, height, config);
        //创建对应的bitmap的画布
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, width, height);
        //把drawable内容画到画布中
        drawable.draw(canvas);
        return bitmap;
    }
}